package com.dylan.channel.v2;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;

public class SingleThreadEventExecutor implements Executor{
    Logger logger=Logger.getLogger(SingleThreadEventExecutor.class.getName());
    Selector selector;
    Thread thread;

    Queue<Runnable> taskQueue;

    public SingleThreadEventExecutor() {
        selector=openSelector();
        taskQueue=new LinkedBlockingQueue<>(1024);
    }

    @Override
    public void execute(Runnable command) {
            if(null==command){
               logger.warning("任务不能为空!");
                return;
            }
            //将任务添加到任务队列
            if(!addTask(command)){
                //TODO 执行拒绝策略
            }

            //启动线程完成任务
            startThread();
    }

    private void startThread() {
        if(thread!=null){
            return;
        }
            new Thread(()->{
                thread=Thread.currentThread();
                SingleThreadEventExecutor.this.run();
            }).start();
    }

    private void run() {
     for (;;){
         try {
             int select = selector.select(3000);
             if(select>0||hasTask()){
                 break;
             }
             processSelectKeys(selector.selectedKeys());
         } catch (IOException e) {
             throw new RuntimeException(e);
         }finally {
             runAllTask();
         }
     }

    }

    private void runAllTask() {
        Runnable task = taskQueue.poll();
        if(Objects.isNull(task)){
            return;
        }
        for (;;){
            task.run();
            task = taskQueue.poll();
            if(Objects.isNull(task)){
                return;
            }
        }
    }

    private void processSelectKeys(Set<SelectionKey> keys) {
        Iterator<SelectionKey> iterator = keys.iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();
            iterator.remove();
            processSelectKey(key);
        }
    }

    private void processSelectKey(SelectionKey key) {
        try {
            if(key.isReadable()){
                SocketChannel channel = (SocketChannel) key.channel();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int read = channel.read(buffer);
                if(read==-1){
                    channel.close();
                    key.cancel();
                    return;
                }
                buffer.flip();
                logger.info("接受到客户端发过来的消息:"+new String(buffer.array(), StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            e.printStackTrace();
            key.cancel();
        }
    }

    private boolean hasTask() {
        return !taskQueue.isEmpty();
    }

    private boolean addTask(Runnable command) {
        if(Objects.isNull(command)){
            logger.warning("任务不能为空!");
           throw new RuntimeException("任务不能为空!");
        }
        return taskQueue.offer(command);
    }

    private Selector openSelector() {
        Selector wrapSelector = null;
        try {
            wrapSelector = SelectorProvider.provider().openSelector();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return wrapSelector;
    }


    public  void register(SocketChannel channel){
        this.execute(new Runnable() {
            @Override
            public void run() {
                register0(channel);
            }
        });
    }
    private void register0(SocketChannel channel) {
        try {
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            logger.info("接受到客户端连接:"+channel.getRemoteAddress().toString());
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            buffer.put("该客户端已经连接成功".getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            channel.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
